﻿using FineUIPro;
using KPI_SYSTEM.Code;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace KPI_SYSTEM.DictPage
{
    public partial class Dept_Dict : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadBaseData();
                BindData();
            }
            PublicMethod.GetApprovalButton("Dept_Dict.aspx", Toolbar2, Grid1);
        }

        /// <summary>
        /// 加载页面必备数据
        /// </summary>
        private void LoadBaseData()
        {

            DataTable tableParentDept = SqlHelper.ExecuteDataset(CommandType.Text, "SELECT DING_CODE,DEPT_NAME FROM DEPT_DICT WHERE DEPT_STATUS=1").Tables[0];
            ddlFormPARENT_ID.DataTextField = "DEPT_NAME";
            ddlFormPARENT_ID.DataValueField = "DING_CODE";
            ddlFormPARENT_ID.DataSource = tableParentDept;
            ddlFormPARENT_ID.DataBind();
            FineUIPro.ListItem parentDeptItem = new FineUIPro.ListItem();
            parentDeptItem.Value = "0";
            parentDeptItem.Text = "无";
            ddlFormPARENT_ID.Items.Insert(0, parentDeptItem);
        }

        /// <summary>
        /// 加载页面列表数据
        /// </summary>
        private void BindData()
        {
            String mainDataSql = @"SELECT A.REC_ID,A.DEPT_NAME,A.PARENT_ID,A.DEPT_CODE,A.DING_CODE,A.WARD_CODE,A.DEPT_TYPE,A.DEPT_STATUS,A.DEPT_REMARK,
                                   (SELECT DEPT_NAME FROM DEPT_DICT WHERE DING_CODE=A.PARENT_ID) AS PATENT_NAME,
                                   CASE WHEN A.DEPT_STATUS=1 THEN '启用' WHEN A.DEPT_STATUS=0 THEN '停用' END AS DEPT_STATUS_NAME FROM DEPT_DICT AS A ";
            DataTable mainDataTable = SqlHelper.ExecuteDataset(CommandType.Text, mainDataSql).Tables[0];
            Grid1.DataSource = mainDataTable;
            Grid1.DataBind();
        }

        // 根据行ID来删除行数据
        private void DeleteRowByID(int rowID)
        {
            try
            {
                SqlHelper.ExecuteNonQuery(CommandType.Text, "UPDATE DEPT_DICT SET DEPT_STATUS=100 WHERE REC_ID=" + rowID);
            }
            catch (Exception ex)
            {
                throw new Exception("删除失败！");
            }
        }

        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                int rowID = Convert.ToInt32(Grid1.DataKeys[e.RowIndex][0]);
                try
                {
                    DeleteRowByID(rowID);
                    BindData();
                    ShowNotify("删除数据成功!");

                }
                catch (Exception ex)
                {
                    ShowNotify("删除数据失败!");
                }
            }
        }
        protected void Grid1_PreRowDataBound(object sender, GridPreRowEventArgs e)
        {
            // 如果绑定到 DataTable，那么这里的 DataItem 就是 DataRowView
            DataRowView row = e.DataItem as DataRowView;
            int rowId = Convert.ToInt32(row["REC_ID"]);

            LinkButtonField editField = Grid1.FindColumn("Edit") as LinkButtonField;
            editField.OnClientClick = String.Format("showEditWindow('{0}');", rowId);
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                Dictionary<String, String> keyValuePairs = new Dictionary<string, string>();
                keyValuePairs.Clear();
                if (tbxFormDEPT_NAME.Text.Trim() != "")
                {
                    keyValuePairs.Add("DEPT_NAME", tbxFormDEPT_NAME.Text.Trim());
                }
                else
                {
                    ShowNotify("部门名称不能为空!");
                    return;
                }
                if (ddlFormPARENT_ID.SelectedValue != "" && ddlFormPARENT_ID.SelectedValue != null)
                {
                    keyValuePairs.Add("PARENT_ID", ddlFormPARENT_ID.SelectedValue);
                }
                //if (tbxFormDEPT_CODE.Text.Trim() != "")
                //{
                //    keyValuePairs.Add("DEPT_CODE", tbxFormDEPT_CODE.Text.Trim());
                //}
                //else
                //{
                //    ShowNotify("部门编号不能为空!");
                //    return;
                //}
                if (tbxFormDING_CODE.Text.Trim() != "")
                {
                    keyValuePairs.Add("DING_CODE", tbxFormDING_CODE.Text.Trim());
                }
                //if (tbxFormWARD_CODE.Text.Trim() != "")
                //{
                //    keyValuePairs.Add("WARD_CODE", tbxFormWARD_CODE.Text.Trim());
                //}
                //if (ddlFormDEPT_TYPE.SelectedValue != "" && ddlFormDEPT_TYPE.SelectedValue != null)
                //{
                //    keyValuePairs.Add("DEPT_TYPE", ddlFormDEPT_TYPE.SelectedValue);
                //}
                //else
                //{
                //    ShowNotify("部门类别不能为空!");
                //    return;
                //}
                if (ddlFormDEPT_STATUS.SelectedValue != "" && ddlFormDEPT_STATUS.SelectedValue != null)
                {
                    keyValuePairs.Add("DEPT_STATUS", ddlFormDEPT_STATUS.SelectedValue);
                }
                else
                {
                    ShowNotify("部门状态不能为空!");
                    return;
                }
                if (tbxFormDEPT_REMARK.Text.Trim() != "")
                {
                    keyValuePairs.Add("DEPT_REMARK", tbxFormDEPT_REMARK.Text.Trim());
                }
                String strRowID = hfFormID.Text;
                if (String.IsNullOrEmpty(strRowID))
                {
                    PublicMethod.SetDataMethod("SELECT * FROM DEPT_DICT WHERE 1=2", "Add", keyValuePairs);
                    ShowNotify("保存成功!");
                }
                else
                {
                    keyValuePairs.Add("REC_ID", strRowID);
                    PublicMethod.SetDataMethod("SELECT * FROM DEPT_DICT WHERE REC_ID="+ strRowID, "Update", keyValuePairs);
                    ShowNotify("保存成功!");
                }
                // 重新绑定表格，并点击当前编辑或者新增的行
                BindData();
                PageContext.RegisterStartupScript(String.Format("F('{0}').selectRow('{1}');", Grid1.ClientID, "1") + Window1.GetHideReference());
            }
            catch (Exception ex)
            {

                throw new Exception("保存失败！");
            }

        }

        protected void btnSyncDept_Click(object sender, EventArgs e)
        {
            try
            {
                List<DING_DEPT_INFO> dEPT_INFOs = new List<DING_DEPT_INFO>();
                dEPT_INFOs = DingHelper.GetDeptList();
                StringBuilder sqlUpdate = new StringBuilder();
                StringBuilder sqlInsert = new StringBuilder();
                foreach (DING_DEPT_INFO dEPT_INFO in dEPT_INFOs)
                {
                    int checkCount = (int)SqlHelper.ExecuteScalar(CommandType.Text, "SELECT COUNT(*) FROM DEPT_DICT WHERE PARENT_ID='" + dEPT_INFO.PARENT_ID + "' AND DING_CODE='" + dEPT_INFO.DING_CODE + "'");
                    if (checkCount > 0)
                    {
                        sqlUpdate.Append("UPDATE DEPT_DICT SET DEPT_NAME='" + dEPT_INFO.DEPT_NAME + "' WHERE PARENT_ID='" + dEPT_INFO.PARENT_ID + "' AND DING_CODE='" + dEPT_INFO.DING_CODE + "';");
                    }
                    else
                    {
                        sqlInsert.Append("INSeRT INTO DEPT_DICT (DEPT_NAME,DING_CODE,PARENT_ID,DEPT_STATUS) VALUES ('" + dEPT_INFO.DEPT_NAME + "','" + dEPT_INFO.DING_CODE + "','" + dEPT_INFO.PARENT_ID + "',1);");
                    }
                }
                if (!String.IsNullOrEmpty(sqlUpdate.ToString()))
                {
                    SqlHelper.ExecuteNonQuery(CommandType.Text, sqlUpdate.ToString());
                }
                if (!String.IsNullOrEmpty(sqlInsert.ToString()))
                {
                    SqlHelper.ExecuteNonQuery(CommandType.Text, sqlInsert.ToString());
                }
                ShowNotify("同步完成");
                BindData();
            }
            catch (Exception ex)
            {

                throw new Exception("保存失败！");
            }

        }
    }
}